import React from 'react';
import {connect} from 'dva/index';
import {Button, Col, Form, InputNumber, Modal, Row, Select} from 'antd';

const FormItem = Form.Item;
const R = require("ramda");
const dateFormat = 'YYYY-MM-DD';
const localFeeItemDetail = Form.create()(class LocalFeeItemDetail extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            open: false,
            disabled: false,
            localFeeId: false,
            disableCase: false,
            disableJob: false
        }
    }

    handleOpen = (localFeeId, disabled,disableCase, disableJob) => {
        this.setState({ open: true, disabled, localFeeId: localFeeId , disableCase, disableJob});
    }

    handleCancel = () => {
        this.setState({ open: false });
        this.props.localFeeDetail.dataSource = {};
        this.props.form.resetFields();
    }

    handleConfirm = () => {
        this.props.form.validateFields({ force: true }, (errors, values) => {
            if (errors) return;
            values.id = this.props.localFeeDetail.dataSource && this.props.localFeeDetail.dataSource.id ? this.props.localFeeDetail.dataSource.id : null;
            let localFeeId = R.isNil(this.state.localFeeId) ? null : this.state.localFeeId 
            if (!R.equals(R.pick(Object.keys(values), this.props.localFeeDetail.dataSource), values)) {
                //箱金额校验
                if(!this.state.disableCase){
                    let fee20gp = values.fee20gp;
                    let fee40gp = values.fee40gp;
                    let fee40hq = values.fee40hq;

                    let flag =  true;
                    if(R.isNil(fee20gp)){
                        this.props.form.setFields({fee20gp: {value: fee20gp, errors: [new Error('费用不能为空')],},});
                        flag =false;
                    }
                    if(R.isNil(fee40gp)){
                        this.props.form.setFields({fee40gp: {value: fee40gp, errors: [new Error('费用不能为空')],},});
                        flag =false;
                    }
                    if(R.isNil(fee40hq)){
                        this.props.form.setFields({fee40hq: {value: fee40hq, errors: [new Error('费用不能为空')],},});
                        flag =false;
                    }

                    if(!flag){
                        return
                    }
                    values.feeSingle = 0;

                }else if(!this.state.disableJob){//票金额校验
                    let feeSingle = values.feeSingle;
                    if(R.isNil(feeSingle)){
                        this.props.form.setFields({feeSingle: {value: feeSingle, errors: [new Error('费用不能为空')],},});
                        return;
                    }
                    values.fee20gp = 0;
                    values.fee40gp = 0;
                    values.fee40hq = 0;

                }

                this.props.dispatch({
                    type: R.isNil(values.id) ? 'localFeeDetail/addLocalFeeDetail' : 'localFeeDetail/updateLocalFeeDetail',
                    payload: {
                        ...values,
                        localFeeId: localFeeId,
                        onSuccess: () => {
                            this.handleCancel();
                            if (this.props.refreshList) this.props.refreshList();
                        }
                    }
                })
            }else this.handleCancel();
        });

    }


    handleChange = (value) => {
        let form = this.props.form;
        form.setFieldsValue({ "fee20gp": undefined });
        form.setFieldsValue({ "fee40gp": undefined });
        form.setFieldsValue({ "fee40hq": undefined });
        form.setFieldsValue({ "feeSingle": undefined });

        let dataList = this.props.feeItem.feeItemList ? this.props.feeItem.feeItemList : [];
        R.map((row) => {
            if(row.id == value){
                let disableCase = R.equals("1", row.unit) ? false : true;//1箱 2票
                let disableJob = R.equals("2", row.unit) ? false : true;
                this.setState({disableCase:  disableCase, disableJob :disableJob});
            }

        }, dataList)
    };

    render() {
        let dataSource = this.props.localFeeDetail.dataSource ? this.props.localFeeDetail.dataSource : {};
        let feeItemList = this.props.feeItem.feeItemList ? this.props.feeItem.feeItemList : [];
        let formItemLayout = { labelCol: { span: 8 }, wrapperCol: { span: 14 } };
        const { getFieldDecorator } = this.props.form;


        let footer = [
            <Button key="save" size="large" loading={this.props.loading} onClick={this.handleConfirm.bind(this)} style={{ display: this.state.disabled ? 'none' : 'inline-block' }}>保存</Button>,
            <Button key="cancel" size="large" loading={this.props.loading} onClick={this.handleCancel.bind(this)}>{this.state.disabled ? "关闭" : "取消"}</Button>
        ];
        return (
            <Modal maskClosable={false} visible={this.state.open} width={850} title={"本地费用（附加费）详情"} confirmLoading={this.props.loading} onCancel={this.handleCancel.bind(this)} footer={footer}>
                <Form>
                    <Row>
                        <Col span={12}>
                            <FormItem {...formItemLayout} label="本地费用代码" hasFeedback>
                                {getFieldDecorator('feeItemId', {
                                    rules: [{
                                        required: true, message: '请选择本地费用代码'
                                    }],
                                    initialValue: (R.isNil(dataSource.feeItemId) || R.isEmpty(dataSource.feeItemId)) ? undefined : dataSource.feeItemId + ""
                                })(
                                    <Select style={{ width: '100%' }} disabled={this.state.disabled} showSearch placeholder="可通过输入关键字搜索"  onChange={this.handleChange.bind(this)}
                                            filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}>
                                        {
                                            !R.isNil(feeItemList) ? feeItemList.map(item => {
                                                return (<Select.Option value={item.id + ""} key={item.id + ""}>{item.name + "[" + item.code + "]"}</Select.Option>);
                                            }) : ''
                                        }
                                    </Select>
                                )}
                            </FormItem>
                        </Col>

                        <Col span={12}>
                            <FormItem {...formItemLayout} label="币种" hasFeedback>
                                {getFieldDecorator('currency', {
                                    rules: [{
                                        required: true, message: '请选择币种',
                                    }],
                                    initialValue: dataSource.currency
                                })(
                                    <Select disabled={this.state.disabled}>
                                        <Select.Option value="CNY">CNY人民币</Select.Option>
                                        <Select.Option value="USD">USD美元</Select.Option>
                                    </Select>
                                    )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={12}>
                            <FormItem {...formItemLayout} label="20GP" hasFeedback>
                                {getFieldDecorator('fee20gp', {
                                    initialValue: dataSource.fee20gp
                                })(
                                    <InputNumber disabled={this.state.disabled || this.state.disableCase} min={0} max={99999999999} maxLength="18" style={{ width: '100%' }} />
                                    )}
                            </FormItem>
                        </Col>
                        <Col span={12}>
                            <FormItem {...formItemLayout} label="40GP" hasFeedback>
                                {getFieldDecorator('fee40gp', {
                                    initialValue: dataSource.fee40gp
                                })(
                                    <InputNumber disabled={this.state.disabled || this.state.disableCase} min={0} max={99999999999} maxLength="18" style={{ width: '100%' }} />
                                    )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={12}>
                            <FormItem {...formItemLayout} label="40HQ" hasFeedback>
                                {getFieldDecorator('fee40hq', {
                                    initialValue: dataSource.fee40hq
                                })(
                                    <InputNumber disabled={this.state.disabled || this.state.disableCase} min={0} max={99999999999} maxLength="18" style={{ width: '100%' }} />
                                    )}
                            </FormItem>
                        </Col>
                        <Col span={12}>
                            <FormItem {...formItemLayout} label="单票" hasFeedback>
                                {getFieldDecorator('feeSingle', {
                                    initialValue: dataSource.feeSingle
                                })(
                                    <InputNumber disabled={this.state.disabled || this.state.disableJob} min={0} max={99999999999} maxLength="18" style={{ width: '100%' }} />
                                    )}
                            </FormItem>
                        </Col>
                    </Row>
                </Form>
            </Modal >
        )
    }
})

function mapStateToProps(state) {
    return {
        loading: state.loading.models.localFeeDetail, localFeeDetail: state.localFeeDetail, feeItem: state.feeItem
    };
}

export default connect(mapStateToProps)(localFeeItemDetail);